<template>
	<u-modal :show="showModal"  :closeOnClickOverlay="true" :showConfirmButton="false" @close="showModal = false" width="300">
		<!-- 生成图片区域 -->
		<view v-if="showGeneratePanel" class="generate-panel">
			<view class="loading-view" v-if="generating">
				<u-loading-icon size="40" color="#0057b8"></u-loading-icon>
				<text class="loading-text">正在生成分享图片...</text>
			</view>

			<view class="preview-view" v-else-if="shareImage">
				<!-- <view class="preview-title">图片预览</view> -->
				<view class="image-container">
					<image :src="shareImage" mode="widthFix" class="preview-image"></image>
				</view>
				<view class="action-buttons">
					<u-button @click="nextStep" class="action-btn save-btn" >
						分享
						<u-icon name="arrow-right" slot="suffix" size="20"></u-icon>
					</u-button>
					<u-button @click="saveImage" class="action-btn  next-btn" :loading="savingImage">
						<u-icon name="download" slot="prefix" size="20"></u-icon>
						保存图片
					</u-button>
				</view>
			</view>

<!-- 			<view class="generate-view" v-else>
				<view class="generate-icon">
					<u-icon name="image" size="60" color="#0057b8"></u-icon>
				</view>
				<view class="generate-title">生成分享图片</view>
				<view class="generate-desc">
					将生成一张包含当前内容的图片，您可以保存或分享给他人
				</view>
				<u-button @click="generateImage" class="generate-btn" type="primary" :loading="generating">
					生成图片
				</u-button>
			</view> -->
		</view>

		<!-- 分享方式选择区域 -->
		<view v-if="showSharePanel" class="share-panel">
			<view class="share-title">选择分享方式</view>
			<view class="share-options">
				<view class="share-option" @click="shareToContact">
					<view class="option-icon">
						<u-icon name="user" size="40" color="#0057b8"></u-icon>
					</view>
					<view class="option-text">分享到联系人</view>
				</view>
				<view class="share-option" @click="shareToMoments">
					<view class="option-icon">
						<u-icon name="chat" size="40" color="#0057b8"></u-icon>
					</view>
					<view class="option-text">分享到朋友圈</view>
				</view>
				<view class="share-option" @click="openChatWindow" v-if="sdkInitialized">
					<view class="option-icon">
						<u-icon name="comment" size="40" color="#0057b8"></u-icon>
					</view>
					<view class="option-text">打开聊天窗口</view>
				</view>
				<!-- H5环境下的分享选项 -->
				<!--        <view class="share-option" @click="copyLink" v-if="!isWeComEnv()">
          <view class="option-icon">
            <u-icon name="link" size="40" color="#0057b8"></u-icon>
          </view>
          <view class="option-text">复制链接</view>
        </view> -->
			</view>
			<u-button @click="prevStep" class="back-btn" type="default">
				<u-icon name="arrow-left" slot="prefix" size="20"></u-icon>
				返回
			</u-button>
		</view>

		<!-- 分享结果提示 -->
		<view v-if="showResultPanel" class="result-panel">
			<view class="result-icon" :class="resultSuccess ? 'success' : 'error'">
				<u-icon :name="resultSuccess ? 'checkmark-circle' : 'close-circle'" size="60"
					:color="resultSuccess ? '#4cd964' : '#ff3b30'"></u-icon>
			</view>
			<view class="result-title">{{ resultTitle }}</view>
			<view class="result-desc">{{ resultDesc }}</view>
			<u-button @click="closeModal" class="confirm-btn" type="primary">
				确定
			</u-button>
		</view>
	</u-modal>
</template>

<script>
	import {
		generateShareImage
	} from '@/utils/canvas-utils.js';
	import {
		isWeComEnv,
		shareToContact,
		shareToMoments,
		saveImageToAlbum,
		getWxUserInfo,
		openChat
	} from '@/utils/wecom-api.js';
	import {
		showToast
	} from '@/utils/toast.js';
	import {
		initWxWork,
		shareMessage
	} from '@/utils/wxWork.js'

	export default {
		name: 'ShareModal',
		props: {
			// 分享内容配置
			shareConfig: {
				type: Object,
				default: () => ({
					title: '',
					content: '',
					logo: '',
					userName: '',
					date: new Date().toLocaleDateString(),
					bgColor: '#ffffff',
					shareUrl: window.location.href // H5环境下的分享链接
				})
			},
			// 是否自动生成图片
			autoGenerate: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				showModal: false,
				// 面板状态
				showGeneratePanel: true,
				showSharePanel: false,
				showResultPanel: false,
				// 生成图片状态
				generating: false,
				shareImage: '',
				// 保存图片状态
				savingImage: false,
				// 分享结果
				resultSuccess: false,
				resultTitle: '',
				resultDesc: '',
				// SDK初始化状态
				sdkInitialized: false,
				// 用户信息
				userInfo: null
			};
		},
		watch: {
			showModal(val) {
				if (val && this.autoGenerate) {
					// 自动生成图片
					this.generateImage();
				}

				if (!val) {
					// 重置状态
					this.resetState();
				}
			}
		},

		methods: {
			/**
			 * 打开分享弹窗
			 */
			open() {
				this.showModal = true;
				this.generateImage();
				// 初始化企业微信SDK
				this.initWeCom();
			},

			/**
			 * 关闭分享弹窗
			 */
			closeModal() {
				this.showModal = false;
				this.$emit('close');
			},

			/**
			 * 重置状态
			 */
			resetState() {
				this.showGeneratePanel = true;
				this.showSharePanel = false;
				this.showResultPanel = false;
				this.generating = false;
				this.shareImage = '';
				this.savingImage = false;
			},

			/**
			 * 初始化企业微信SDK
			 */
			async initWeCom() {
				try {
					// 指定需要使用的接口（按需添加）
					const jsApiList = ['onMenuShareAppMessage', 'onMenuShareWechat', 'shareAppMessage','shareWechatMessage']
					await initWxWork(jsApiList)
					console.log("初始化成功");
				} catch (err) {
					console.log('初始化失败');
				}
			},

			/**
			 * 生成分享图片
			 */
			async generateImage() {
				try {
					this.generating = true;

					// 生成图片
					this.shareImage = await generateShareImage(this.shareConfig);

					// 生成成功
					this.generating = false;

					// 如果是自动生成，直接进入分享面板
					if (this.autoGenerate) {
						this.nextStep();
					}
				} catch (error) {
					console.error('生成分享图片失败:', error);
					this.generating = false;

					// 显示错误提示
					uni.showToast({
						title: '生成图片失败',
						icon: 'none'
					});
				}
			},

			/**
			 * 保存图片到相册
			 */
			async saveImage() {
				if (!this.shareImage) {
					uni.showToast({
						title: '请先生成图片',
						icon: 'none'
					});
					return;
				}

				try {
					this.savingImage = true;

					// 保存图片
					await saveImageToAlbum(this.shareImage);

					this.savingImage = false;

					// 显示成功提示
					uni.showToast({
						title: '图片已保存到相册',
						icon: 'success'
					});
				} catch (error) {
					console.error('保存图片失败:', error);
					this.savingImage = false;

					// 显示错误提示
					uni.showToast({
						title: error.message || '保存图片失败',
						icon: 'none'
					});
				}
			},

			/**
			 * 下一步：进入分享方式选择
			 */
			nextStep() {

				// this.showSharePanel = true;
				// this.showGeneratePanel = false;
				// 看是否在企业微信中
				// 检查是否在企业微信环境
				if (!isWeComEnv()) {
					uni.showToast({
						title:'企微'
					})
					return;
				}
				
				this.shareToContact()
			},

			/**
			 * 上一步：返回图片生成面板
			 */
			prevStep() {
				this.showSharePanel = false;
				this.showGeneratePanel = true;
			},

			/**
			 * 分享到联系人
			 */
			async shareToContact() {
				if (!this.shareImage) {
					uni.showToast({
						title: '请先生成图片',
						icon: 'none'
					});
					return;
				}

				try {
					
					// 分享图片
					await shareMessage({
						title: this.shareConfig.title,
						desc:this.shareConfig.content,
						link:this.shareConfig.shareUrl,
						imgUrl: this.shareImage,
					});

					// 显示成功结果
					this.showShareResult(true, '分享成功', '图片已成功分享给联系人');
				} catch (error) {
					console.error('分享到联系人失败:', error);

					// 显示失败结果
					this.showShareResult(false, '分享失败', error.message || '分享到联系人失败，请重试');
				}
			},

			/**
			 * 打开企业微信聊天窗口
			 */
			async openChatWindow() {
				try {
					// 检查是否在企业微信环境
					if (!isWeComEnv()) {
						this.showShareResult(false, '操作失败', '请在企业微信客户端中打开以使用此功能');
						return;
					}

					// 检查SDK是否初始化
					if (!this.sdkInitialized) {
						await this.initWeCom();
					}

					// 打开聊天窗口（示例：打开与当前用户的聊天）
					const options = {
						userIds: this.userInfo?.userId || '', // 企业内部用户ID
						groupName: '分享讨论' // 群聊名称
					};

					await openChat(options);

					// 显示成功结果
					this.showShareResult(true, '操作成功', '已打开聊天窗口');
				} catch (error) {
					console.error('打开聊天窗口失败:', error);

					// 显示失败结果
					this.showShareResult(false, '操作失败', error.message || '打开聊天窗口失败，请重试');
				}
			},

			/**
			 * 分享到朋友圈
			 */
			async shareToMoments() {
				if (!this.shareImage) {
					uni.showToast({
						title: '请先生成图片',
						icon: 'none'
					});
					return;
				}

				try {
					// 检查是否在企业微信环境
					if (!isWeComEnv()) {
						// 非企业微信环境，直接保存图片
						await saveImageToAlbum(this.shareImage);
						this.showShareResult(true, '保存成功', '图片已保存到相册，请手动分享到朋友圈');
						return;
					}

					// 检查SDK是否初始化
					if (!this.sdkInitialized) {
						await this.initWeCom();
					}

					// 分享图片
					await shareToMoments({
						imageUrl: this.shareImage,
						content: this.shareConfig.content
					});

					// 显示成功结果
					this.showShareResult(true, '分享成功', '图片已成功分享到朋友圈');
				} catch (error) {
					console.error('分享到朋友圈失败:', error);

					// 显示失败结果
					this.showShareResult(false, '分享失败', error.message || '分享到朋友圈失败，请重试');
				}
			},

			/**
			 * 复制链接（H5环境）
			 */
			copyLink() {
				try {
					// 获取分享链接
					const shareUrl = this.shareConfig.shareUrl || window.location.href;

					// 创建临时输入框
					const input = document.createElement('input');
					input.value = shareUrl;
					document.body.appendChild(input);
					input.select();

					// 复制到剪贴板
					document.execCommand('copy');

					// 移除临时输入框
					document.body.removeChild(input);

					// 显示成功提示
					this.showShareResult(true, '复制成功', '链接已复制到剪贴板');
				} catch (error) {
					console.error('复制链接失败:', error);

					// 显示失败结果
					this.showShareResult(false, '复制失败', '复制链接失败，请手动复制');
				}
			},

			/**
			 * 显示分享结果
			 */
			showShareResult(success, title, desc) {
				this.resultSuccess = success;
				this.resultTitle = title;
				this.resultDesc = desc;

				this.showSharePanel = false;
				this.showResultPanel = true;

				// 触发结果回调
				this.$emit('result', {
					success,
					title,
					desc
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.generate-panel,
	.share-panel,
	.result-panel {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx 0;
	}

	/* 生成图片面板样式 */
	.loading-view {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 0;

		.loading-text {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #666;
		}
	}

	.preview-view {
		width: 100%;

		.preview-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
			text-align: center;
		}

		.image-container {
			width: 100%;
			display: flex;
			justify-content: center;
			margin-bottom: 30rpx;

			.preview-image {
				width: 100%;
				border-radius: 16rpx;
				box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
			}
		}

		.action-buttons {
			display: flex;
			justify-content: space-between;
			width: 100%;
			margin: 0 auto;

			.action-btn {
				width: 48%;
				height: 80rpx;
				font-size: 28rpx;

				&.save-btn {
					background-color: #f5f7fa;
					color: #333;
				}

				&.next-btn {
					background-color: #d81e06;
					border: none;
					color: #fff;
				}
			}
		}
	}

	.generate-view {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 60rpx 0;

		.generate-icon {
			margin-bottom: 30rpx;
		}

		.generate-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 15rpx;
		}

		.generate-desc {
			font-size: 26rpx;
			color: #666;
			text-align: center;
			padding: 0 40rpx;
			margin-bottom: 40rpx;
			line-height: 1.6;
		}

		.generate-btn {
			width: 60%;
			height: 88rpx;
			font-size: 30rpx;
			background-color: #0057b8;
			color: #fff;
		}
	}

	/* 分享方式面板样式 */
	.share-panel {
		.share-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 40rpx;
		}

		.share-options {
			display: flex;
			justify-content: space-around;
			width: 100%;
			margin-bottom: 60rpx;
			flex-wrap: wrap;
			/* 支持换行 */

			.share-option {
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 30%;
				margin-bottom: 20rpx;

				.option-icon {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					background-color: #f0f7ff;
					display: flex;
					justify-content: center;
					align-items: center;
					margin-bottom: 20rpx;
				}

				.option-text {
					font-size: 26rpx;
					color: #333;
					text-align: center;
					word-break: break-word;
					padding: 0 10rpx;
				}
			}
		}

		.back-btn {
			width: 60%;
			height: 80rpx;
			font-size: 28rpx;
		}
	}

	/* 分享结果面板样式 */
	.result-panel {
		.result-icon {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 30rpx;

			&.success {
				background-color: #f0fff4;
			}

			&.error {
				background-color: #fff0f0;
			}
		}

		.result-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 15rpx;
		}

		.result-desc {
			font-size: 26rpx;
			color: #666;
			text-align: center;
			padding: 0 40rpx;
			margin-bottom: 40rpx;
			line-height: 1.6;
		}

		.confirm-btn {
			width: 60%;
			height: 88rpx;
			font-size: 30rpx;
			background-color: #0057b8;
			color: #fff;
		}
	}
</style>